//
//  GetAddBuyGoodsViewController.m
//  TryShopping
//
//  Created by panquanReabam.com on 16/10/19.
//  Copyright © 2016年 RuiBen. All rights reserved.
//

#import "GetAddBuyGoodsViewController.h"
#import "scanViewController.h"
#import "ZJSwitch.h"
#import "MJRefresh.h"
#import "GetAddBuyGoodsCell.h"
#import "GetAddBuyGoodsModel.h"
#import "SelectedGoodNewViewController1.h"
#import "GatherSingleViewController.h"
@interface GetAddBuyGoodsViewController ()<UIGestureRecognizerDelegate,UINavigationControllerDelegate,UITextFieldDelegate,UITextViewDelegate,UITableViewDelegate,UITableViewDataSource,scanViewControllerDelegate>
@end
@implementation GetAddBuyGoodsViewController
{
    NSMutableArray*title;
    NSMutableArray*couponId ;
    NSMutableArray*price ;
    NSMutableArray*couponIds ;
    NSMutableArray*headerModelArray ;
    NSString* userToken;
    NSString*pid;
    NSString*specId;
    NSString*itemId;
    NSString*isSelect;
    UIView*noDataView;
    UITextField*searchTextField;
    UIView*HeaderView;
    UILabel *planTitleLabel;
   }
@synthesize alt = alt;

-(void)BackAction:(UIButton *)sender{
    
    [self.navigationController popViewControllerAnimated:YES];
}
- (void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
    self.navigationController.delegate = nil;
    
}
-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
  
    [[self rdv_tabBarController] setTabBarHidden:YES];
    self.navigationController.navigationBarHidden=NO;
    self.navigationController.navigationBar.barStyle = UIBaselineAdjustmentNone;
    UILabel *lineLabel=[[UILabel alloc] initWithFrame:CGRectMake(0, 43,ScreenWidth, 1)];
    [lineLabel setBackgroundColor:[UIColor colorWithRed:238/255.0 green:238/255.0 blue:238/255.0 alpha:1]];
    lineLabel.alpha=1;
    [self.navigationController.navigationBar addSubview:lineLabel];
    [self.navigationController.navigationBar setTintColor:[UIColor whiteColor]];
    [[UINavigationBar appearance] setBarTintColor:Color];
    UIImage* backImage = [UIImage imageNamed:@"fanhui"];
    CGRect backframe = CGRectMake(0,0,30,30);
    UIButton* backButton= [[UIButton alloc] initWithFrame:backframe];
    [backButton setBackgroundImage:backImage forState:UIControlStateNormal];
    backButton.titleLabel.textAlignment=NSTextAlignmentLeft;
    [backButton addTarget:self action:@selector(BackAction:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem* leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:backButton];
    self.navigationItem.leftBarButtonItem = leftBarButtonItem;
    UIView*titleView=[[UIView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, 32.5)];
    titleView.backgroundColor=zuiqianhuiColor;
    self.navigationItem.titleView=titleView;
    
    
    UIButton *sxBtn1 = [[UIButton alloc] initWithFrame:CGRectMake( 5, 5, 25, 25)];
    [sxBtn1 setImage:[UIImage imageNamed:@"sousuo"] forState:UIControlStateNormal];
    [titleView addSubview:sxBtn1];
    
    
    searchTextField = [[UITextField alloc] initWithFrame:CGRectMake(sxBtn1.right,0, ScreenWidth*400/750,35)];
    [searchTextField setBorderStyle:   UITextBorderStyleNone]; //外框类型
    searchTextField.placeholder = @" 请输入条形码／商品名"; //默认显示的字
    searchTextField.font = [UIFont systemFontOfSize: 14];
    searchTextField.tag=22;
//    searchTextField.keyboardType = UIKeyboardTypeDecimalPad;
    searchTextField.returnKeyType = UIReturnKeyDone;
    searchTextField.clearButtonMode = UITextFieldViewModeWhileEditing; //编辑时会出现个修改X
    searchTextField.delegate = self;
    [titleView addSubview:searchTextField];
    
    UIView* myToolBar=[[UIView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, viewheight)];
    myToolBar.backgroundColor=jianpancolor;
    UIButton*  tubtnDone=[[UIButton alloc]initWithFrame:CGRectMake(logoX,logoY, logoheight, logowidth)];
    [tubtnDone setImage:[UIImage imageNamed:@""] forState:UIControlStateNormal];
    [tubtnDone addTarget:self action:@selector(OnTapDone) forControlEvents:UIControlEventTouchUpInside];
    [myToolBar addSubview:tubtnDone];
    UIButton*btnDone111=[[UIButton alloc]initWithFrame:CGRectMake(myToolBar.frame.size.width - 55, 12, 40, 16)];
    [btnDone111 setTitle:@"确定" forState:UIControlStateNormal];
    [btnDone111 setTitleColor:jianpancolor1 forState:UIControlStateNormal];
    btnDone111 .titleLabel .font=[UIFont systemFontOfSize:16];
    [btnDone111 addTarget:self action:@selector(OnTapDone) forControlEvents:UIControlEventTouchUpInside];
    [myToolBar addSubview:btnDone111];
    myToolBar.alpha=alp;
    UIButton* dabtn=[[UIButton alloc]initWithFrame:CGRectMake(myToolBar.frame.size.width-60, 0, 60, 40)];
    [dabtn addTarget:self action:@selector(OnTapDone) forControlEvents:UIControlEventTouchUpInside];
    [myToolBar addSubview:dabtn];
    searchTextField.inputAccessoryView = myToolBar;
    
    
    self.navigationController.navigationBar.barStyle =UIBaselineAdjustmentNone ;
   
    UIButton* operationsBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0.0,  60/2, 60/2)];
    [operationsBtn setBackgroundImage:[UIImage imageNamed:@"saoyisao_new"] forState:UIControlStateNormal];
    [operationsBtn addTarget:self action:@selector(operations:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem* myBtnBtn = [[UIBarButtonItem alloc] initWithCustomView:operationsBtn];
    self.navigationItem.rightBarButtonItem = myBtnBtn;

    
}
-(void)operations:(UIButton*)sender{
    
    scanViewController *detailViewController = [[scanViewController alloc] init];
     detailViewController.delegate=self;
    //detailViewController.typeString=scanTypeStr;
    
    [self.navigationController pushViewController:detailViewController animated:YES];
    
    
}
-(void)Combination:(UIButton*)sender{
    
    GatherSingleViewController *detailViewController = [[GatherSingleViewController alloc] init];
    detailViewController.shopCartId=_shopCartId;
    [self.navigationController pushViewController:detailViewController animated:YES];
}
-(void)scanGoodInfoData:(NSString*)codeStr{
    searchTextField.text=codeStr;
    [self requestData];
}
-(void)OnTapDone{
    
    [searchTextField resignFirstResponder];
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [self requestData];
    
    [searchTextField resignFirstResponder];
    return YES;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
   
   
    [_tableView registerClass:[GetAddBuyGoodsCell class] forCellReuseIdentifier:@"GetAddBuyGoodsViewController"];
    _tableView.separatorStyle=UITableViewCellSeparatorStyleNone;
   
    HeaderView=[[UIView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, 40)];
    _tableView.tableHeaderView=HeaderView;
    HeaderView.backgroundColor=zuiqianhuiColor;
   
    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
    userToken = [user objectForKey:@"tokenId"];
   
    
    [self   requestData];
    [self   setAutoLayout];
}

-(void)requestData{
    
    
    [noDataView removeFromSuperview];
    [planTitleLabel removeFromSuperview];
    
    headerModelArray=[[NSMutableArray alloc]init];
    pid=@"";
   
        NSMutableDictionary *param = [NSMutableDictionary new];
        [param setValue:userToken forKey:@"tokenId"];
        [param setValue:self.shopCartId forKey:@"shopCartId"];
        [param setValue:searchTextField.text forKey:@"sword"];
        [Global showIndeterminateHudSub:@"加载中，请稍后。。。" delay:30 view:self.view];
        NSLog(@"-----%@",param);
        [HttpRequest requestData:@"Business/ShopCart/NGifts" params:param success:^(BOOL isSuccess, SeverData *severDataDict) {
            if (isSuccess) {
                NSLog(@"-----%@",severDataDict.dataDict);
                if ([[severDataDict.dataDict objectForKey:@"ResultInt"] integerValue]==0) {
                    [Global hideProgressHUDInternal:self.view];

                   planTitleLabel=[[UILabel alloc] initWithFrame:CGRectMake(15, 0,ScreenWidth-100, 40)];
                    planTitleLabel.text=[NSString stringWithFormat:@"%@",[severDataDict.dataDict objectForKey:@"planTitle"] ];
                    planTitleLabel.textColor=zhonghuiColor;
                    planTitleLabel.font=[UIFont systemFontOfSize:13];
                    [HeaderView addSubview:planTitleLabel];
                     if([[NSString stringWithFormat:@"%@",  [severDataDict.dataDict objectForKey:@"planType"]]isEqualToString:@"P003"]) {
                    UIButton*CombinationOfGiftBtn=[[UIButton alloc] initWithFrame:CGRectMake(ScreenWidth-100, 0, 60, 42)];
                    [CombinationOfGiftBtn setTitle:@"继续凑单" forState:UIControlStateNormal];
                    [CombinationOfGiftBtn setTitleColor:[UIColor colorWithRed:255/255.0 green:51/255.0 blue:0/255.0 alpha:1]  forState:UIControlStateNormal];
                    CombinationOfGiftBtn.contentHorizontalAlignment=UIControlContentHorizontalAlignmentRight;
                    CombinationOfGiftBtn .titleLabel.font=[UIFont systemFontOfSize:12];
                    [CombinationOfGiftBtn addTarget:self action:@selector(Combination:) forControlEvents:UIControlEventTouchUpInside];
                    [HeaderView addSubview:CombinationOfGiftBtn];
                    
                    UIButton*chooseBtn1=[[UIButton alloc] initWithFrame:CGRectMake(ScreenWidth-40, 5, 33, 33)];
                    [chooseBtn1 setTitle:@"继续凑单" forState:UIControlStateNormal];
                    [chooseBtn1 setTitleColor:[UIColor clearColor]  forState:UIControlStateNormal];
                    [chooseBtn1 setImage:[UIImage imageNamed:@"shouqi"] forState:UIControlStateNormal];
                    [chooseBtn1 addTarget:self action:@selector(Combination:) forControlEvents:UIControlEventTouchUpInside];
                    [HeaderView addSubview:chooseBtn1];
                     }
                    _totalLabel.text=[NSString stringWithFormat:@"已换领 %@/%@ 件",[severDataDict.dataDict objectForKey:@"getQty"],[severDataDict.dataDict objectForKey:@"giveQty"] ];
                        NSMutableArray *mArray=[NSMutableArray arrayWithArray:[severDataDict.dataDict objectForKey:@"DataLine"]];
                        if (mArray.count==0) {
                            
                            noDataView=[[UIView alloc]initWithFrame:CGRectMake(0, ScreenHeight/2-50, ScreenWidth, 80)];
                            [self.view addSubview:noDataView];
                            UIImageView*noImage=[[UIImageView alloc]initWithFrame:CGRectMake(ScreenWidth/2-47, 0, 94, 51)];
                            noImage.image=[UIImage imageNamed:@"meiyoushuju"];
                            [noDataView addSubview:noImage];
                            UILabel*noLabel=[[UILabel alloc]initWithFrame:CGRectMake(0,65, ScreenWidth, 14)];
                            noLabel.text=@"没有列表数据，赶紧去添加！";
                            noLabel.textColor=zhonghuiColor; noLabel.font=[UIFont systemFontOfSize:14];
                            noLabel.textAlignment=NSTextAlignmentCenter;
                            [noDataView addSubview:noLabel];                           }else{

                        for (NSDictionary* dicc in mArray )
                        {
                            
                            if ([[NSString stringWithFormat:@"%@",  [dicc objectForKey:@"isCurrent"]]isEqualToString:@"Y"]&&[[NSString stringWithFormat:@"%@",  [dicc objectForKey:@"isAvailable"]]isEqualToString:@"Y"]) {
                                pid=[NSString stringWithFormat:@"%@",  [dicc objectForKey:@"pid"]];
                            } //默认的
                            
                            GetAddBuyGoodsModel *model=[GetAddBuyGoodsModel mj_objectWithKeyValues:dicc];
                            [headerModelArray addObject:model];
                            
                        }
                        }
                        [_tableView reloadData];

                   
                }else{
                    [Global hideProgressHUDInternal:self.view];
                    NSString *requestResultStr=[severDataDict.dataDict objectForKey:@"ResultString"];
                    [Global showTextHudSub:requestResultStr view:self.view];
                }}
            else
            {
                [Global hideProgressHUDInternal:self.view];
                [Global showTextHudSub:severDataDict.resultStr view:self.view];
            }
        }];
    

}
- (IBAction)ture:(id)sender {
    [_mDelegate update:@""];
    SelectedGoodNewViewController1 *homeVC1 = [[SelectedGoodNewViewController1 alloc] init];
    UIViewController *target1 = nil;
    for (UIViewController * controller in self.navigationController.viewControllers) { //遍历
        if ([controller isKindOfClass:[homeVC1 class]]) { //这里判断是否为你想要跳转的页面
            target1 = controller;
        }
    }
    [self.navigationController popToViewController:target1 animated:YES]; //跳转
 
   
}

#pragma mark - Table view data source
#pragma mark - Table view delegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [headerModelArray count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    GetAddBuyGoodsCell*cell = [tableView dequeueReusableCellWithIdentifier:@"GetAddBuyGoodsViewController"];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    for (UIView *view in [cell subviews]){
        [view removeFromSuperview];
    }

    cell.GetAddBuyGoodsModel=headerModelArray[indexPath.row];
 
       return cell;
}

- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    return  114;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    [Global showIndeterminateHudSub:@"加载中，请稍后。。。" delay:30 view:self.view];
    GetAddBuyGoodsModel *model=headerModelArray[indexPath.row];
    if ([model.isAvailable isEqualToString:@"Y"]) {
    
    if ([model.isCurrent isEqualToString:@"Y"]) {
    
    isSelect=@"N";
    
    }else{
    
    isSelect=@"Y";

    
    }

        
        pid=model.pid;
        specId=model.specId;
        itemId=model.itemId;
        
            NSMutableDictionary *param = [NSMutableDictionary new];
            [param setValue:userToken forKey:@"tokenId"];
            [param setValue:self.shopCartId forKey:@"shopCartId"];
            [param setValue:pid forKey:@"pid"];
            [param setValue:isSelect forKey:@"isSelect"];
            [param setValue:itemId forKey:@"itemId"];
            [param setValue:specId forKey:@"specId"];
      
            NSLog(@"-----%@",param);
            [HttpRequest requestData:@"Business/ShopCart/NAddGift" params:param success:^(BOOL isSuccess, SeverData *severDataDict) {
                if (isSuccess) {
                    NSLog(@"-----%@",severDataDict.dataDict);
                    if ([[severDataDict.dataDict objectForKey:@"ResultInt"] integerValue]==0) {
                        [Global hideProgressHUDInternal:self.view];
                        [self  requestData];
                    }else{
                        [Global hideProgressHUDInternal:self.view];
                        NSString *requestResultStr=[severDataDict.dataDict objectForKey:@"ResultString"];
                        [Global showTextHudSub:requestResultStr view:self.view];
                    }}
                else
                {
                    [Global hideProgressHUDInternal:self.view];
                    [Global showTextHudSub:severDataDict.resultStr view:self.view];
                }
            }];

        
        }else{
        
            [self showAlertMessage:@"不可以领取！"];
        }
    
    
}
-(void)setAutoLayout
{
    [_tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view.mas_left)  ;
        make.right.equalTo(self.view.mas_right)   ;
        make.bottom.equalTo(self.view.mas_bottom);
        make.top.equalTo(self.view.mas_top).with.offset(0);
    }];
    [_lastView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view.mas_left) ;
        make.right.equalTo(_submitConfirmBtn.mas_left) ;
        make.height.equalTo(@48) ;
        make.bottom.equalTo(self.view.mas_bottom);
        
    }];
    [_submitConfirmBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(self.view.mas_right) ;
        make.width.equalTo(@160) ;
        make.height.equalTo(@48) ;
        make.bottom.equalTo(self.view.mas_bottom);
    }];
    [_totalCountView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view.mas_left) ;
        make.right.equalTo(_submitConfirmBtn.mas_left) ;
        make.height.equalTo(@48) ;
        make.bottom.equalTo(self.view.mas_bottom);
    }];
    
}

- (void)showAlertWait
{
    alt = [[UIAlertView alloc] initWithTitle:@"网络不稳定 ！" message:@"请确认网络" delegate:self cancelButtonTitle:nil otherButtonTitles: nil];
    [alt show];
    
    [self performSelector:@selector(hideAlert) withObject:nil afterDelay:1.0f];
    
}

- (void)showAlertMessage:(NSString *)msg
{
    alt = [[UIAlertView alloc] initWithTitle:@"温馨提示" message:msg delegate:nil cancelButtonTitle:nil otherButtonTitles: nil];
    [alt show];
    
    [self performSelector:@selector(hideAlert) withObject:nil afterDelay:1.0f];
}
- (void)hideAlert
{
    if (alt != nil)
    {
        [alt dismissWithClickedButtonIndex:0 animated:YES];
        alt = nil;
    }
}
@end
